import axios from 'axios';
// import type { AxiosInstance, AxiosRequestConfig } from 'axios';
import type { AxiosInstance } from 'axios';
import type { MYRequestInterceptors, MYRequestConfig } from './type';

import { ElLoading } from 'element-plus';
import { ILoadingInstance } from 'element-plus/lib/el-loading/src/loading.type';

class MYRequest {
  instance: AxiosInstance;
  interceptors?: MYRequestInterceptors;
  loading?: ILoadingInstance;

  constructor(config: MYRequestConfig) {
    this.instance = axios.create(config);
    this.interceptors = config._interceptors;

    // 从config中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );

    // 添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        this.loading = ElLoading.service({
          lock: true,
          text: '加载中....',
          background: 'rgba(0, 0, 0, 0.5)'
        });
        return config;
      },
      (err) => {
        return err;
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        this.loading?.close();
        return res;
      },
      (err) => {
        // 测试git
        this.loading?.close();
        return err;
      }
    );
  }

  _request<T>(config: MYRequestConfig<T>): Promise<T> {
    //Promise的泛型T代表promise变成成功态之后resolve的值，resolve(value)
    return new Promise((resolve) => {
      // 单个请求对请求config的处理
      if (config._interceptors?.requestInterceptor) {
        config = config._interceptors.requestInterceptor(config);
      }
      this.instance.request<any, T>(config).then((res) => {
        // 单个请求对数据的处理
        if (config._interceptors?.responseInterceptor) {
          res = config._interceptors.responseInterceptor(res);
        }
        // 将结果resolve传出去，调用resolve，外面就会调用对应的then方法
        resolve(res);
      });
    });
  }

  get<T>(config: MYRequestConfig<T>): Promise<T> {
    return this._request<T>({ ...config, method: 'GET' });
  }
  post<T>(config: MYRequestConfig<T>): Promise<T> {
    return this._request<T>({ ...config, method: 'POST' });
  }
  delete<T>(config: MYRequestConfig<T>): Promise<T> {
    return this._request<T>({ ...config, method: 'DELETE' });
  }
  patch<T>(config: MYRequestConfig<T>): Promise<T> {
    return this._request<T>({ ...config, method: 'PATCH' });
  }
}

export default MYRequest;
